# -*- coding: UTF-8 -*-


from .x2mtree import X2mTree
from .x2mform import X2mForm

from .formview import FormView

import copy


class Field(object):
    def __init__(self, field_info, env=None, parent=None, **kwargs):
        self.env = env
        self._field_info = field_info
        self.parent_info = parent


class Relation(Field):
    def __init__(self, field_info,  **kwargs):
        super().__init__(field_info, **kwargs)
        self._views = {}

    @property
    def field_info(self):
        info = copy.deepcopy(self._field_info)
        views = info['views'] or {}
        views.update(self._views)
        info['views'] = views
        return info

    @property
    def Model(self):
        model = self.field_info['relation']
        Model = self.env.model(model)
        return Model

    @property
    def tree(self):
        return X2mTree(self.field_info, env=self.env, parent=self.parent_info)

    @property
    def form(self):
        return X2mForm(self.field_info, env=self.env, parent=self.parent_info)

    def _load_views(self):
        meta = self.field_info
        is_x2many_tree = meta['type'] in [
            'one2many', 'many2many'] and meta['widget'] == 'x2many_tree'

        if not is_x2many_tree:
            return {
                'tree': {}, 'kanban': {}, 'form': {}
            }

        meta = copy.deepcopy(meta)
        views = meta.get('views', {})
        treeview = views.get('tree', {})
        formview = views.get('form', {})

        raw_tree = treeview.get('fields', {'display_name': {}})
        raw_form = formview.get('fields', {'display_name': {}})

        fields_raw = {}
        fields_raw.update(raw_tree)
        fields_raw.update(raw_form)
        fields_info = self.Model.fields_get(list(fields_raw.keys()))

        def merge_fields_info(info, raw):
            result = {}
            for fld, val in raw.items():
                result[fld] = copy.deepcopy(info[fld])
                result[fld].update(val)
            return result

        fields_tree = merge_fields_info(fields_info, raw_tree)
        fields_from = merge_fields_info(fields_info, raw_form)

        treeview['fields'] = fields_tree
        formview['fields'] = fields_from

        views_info = {
            'tree': treeview,
            'form': formview
        }

        return views_info

    def load_views(self):
        views = self._load_views()
        self._views = views
        return views
